// 主类
class Solution {
    // 记录左右子树的最大高度差
    int distance = 0;

    public boolean isBalanced(TreeNode root) {
        check(root);
        return distance <= 1;
    }

    public int check(TreeNode a) {
        if (a == null) {
            return 0;
        }

        int left = check(a.left);
        int right = check(a.right);
        // 计算当前节点左右子树的高度差，并更新最大高度差
        distance = Math.max(Math.abs(left - right), distance);

        // 返回当前节点的最大高度
        return 1 + Math.max(left, right);
    }
}

// 定义二叉树节点类
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

// 主程序入口
public class BalancedBinaryTree {
    public static void main(String[] args) {
        // 测试用例1：平衡二叉树
        TreeNode balancedRoot = new TreeNode(1);
        balancedRoot.left = new TreeNode(2);
        balancedRoot.right = new TreeNode(3);
        balancedRoot.left.left = new TreeNode(4);
        balancedRoot.left.right = new TreeNode(5);

        // 测试用例2：不平衡二叉树
        TreeNode unbalancedRoot = new TreeNode(1);
        unbalancedRoot.left = new TreeNode(2);
        unbalancedRoot.left.left = new TreeNode(3);
        unbalancedRoot.left.left.left = new TreeNode(4);

        Solution solution = new Solution();

        // 输出测试结果
        System.out.println("测试用例1是否平衡: " + solution.isBalanced(balancedRoot)); // 应该输出true
        solution.distance = 0; // 重置最大高度差
        System.out.println("测试用例2是否平衡: " + solution.isBalanced(unbalancedRoot)); // 应该输出false
    }
}    